package com.learn.grpc.interceptor;

import io.grpc.*;

/**
 * @author zongf
 * @since 2023-07-06
 **/
public class MyClientInterceptor implements ClientInterceptor {
    @Override
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> methodDescriptor,
                                                               CallOptions callOptions, Channel channel) {
        ClientCall<ReqT, RespT> clientCall = channel.newCall(methodDescriptor, callOptions);
        return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(clientCall) {

            private long start = 0;

            @Override
            public void sendMessage(ReqT message) {
                super.sendMessage(message);
                start = System.currentTimeMillis();
                System.out.println("【MyClientInterceptor】请求参数:" + message);

            }

            @Override
            public void start(Listener<RespT> responseListener, Metadata headers) {
                super.start(new ForwardingClientCallListener.SimpleForwardingClientCallListener<RespT>(responseListener) {
                    @Override
                    public void onMessage(RespT message) {
                        super.onMessage(message);
                        long cost = System.currentTimeMillis() - start;
                        System.out.println("【MyClientInterceptor】cost:" + cost + ",响应参数:" + message );
                    }
                }, headers);
            }
        };
    }
}
